import { store } from "@/store";
import { defineStore } from "pinia";
import { SetupStoreId } from "@/enum";
import { useStorage } from "@vueuse/core";
import { DictVO, fetchGetDictSimpleList } from "@/service/api";

export const useDictStore = defineStore(SetupStoreId.Dict, () => {
  const dictionary = useStorage<Record<string, CommonType.DictOption[]>>("dictCache", {});

  const setDictionary = (dict: DictVO) => {
    dictionary.value[dict.dictCode] = dict.dictDataList;
  };

  const loadDictionaries = async () => {
    const { data: res } = await fetchGetDictSimpleList();
    if (res === null) {
      return;
    }
    res.forEach(setDictionary);
  };

  const getDictionary = (dictCode: string): CommonType.DictOption[] => {
    return dictionary.value[dictCode] || [];
  };

  const clearDictionaryCache = () => {
    dictionary.value = {};
  };

  const updateDictionaryCache = async () => {
    clearDictionaryCache(); // 先清除旧缓存
    await loadDictionaries(); // 重新加载最新字典数据
  };

  return {
    dictionary,
    setDictionary,
    loadDictionaries,
    getDictionary,
    clearDictionaryCache,
    updateDictionaryCache,
  };
})

export function useDictStoreHook() {
  return useDictStore(store);
}
